﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace LabMS.Web.CommonPage
{
    public partial class DownloadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]) && Request.QueryString["Flag"] == "download")
                {
                    if (!IsNumber(Request.QueryString["ID"]))
                    {
                        Page.ClientScript.RegisterClientScriptBlock(GetType(), "script", "<script type='text/javascript'>alert('查询字符串错误');window.close();</script>");
                        return;
                    }
                    LabMS.BLL.AttachmentItem attachItem = new LabMS.BLL.AttachmentItem();
                    LabMS.Model.AttachmentItem attachmodel = new LabMS.Model.AttachmentItem();
                    attachmodel = attachItem.GetModel(int.Parse(Request.QueryString["ID"].Trim()));

                    FileItemDownload(attachmodel.ID, attachmodel.Item_Address, attachmodel.Item_Name);
                    return;
                }
                else if (!string.IsNullOrEmpty(Request.QueryString["ID"]) && Request.QueryString["Flag"] == "attachdownload")
                {
                    if (!IsNumber(Request.QueryString["ID"]))
                    {
                        Page.ClientScript.RegisterClientScriptBlock(GetType(), "script", "<script type='text/javascript'>alert('查询字符串错误');window.close();</script>");
                        return;
                    }
                    LabMS.BLL.Attachment Attach = new LabMS.BLL.Attachment();
                    LabMS.Model.Attachment attachmodel = new LabMS.Model.Attachment();
                    attachmodel = Attach.GetModel(int.Parse(Request.QueryString["ID"].Trim()));

                    FileItemDownload(attachmodel.ID, attachmodel.Attach_Address, attachmodel.Attach_Name);
                    return;
                }
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    if (!IsNumber(Request.QueryString["ID"]))
                    {
                        Page.ClientScript.RegisterClientScriptBlock(GetType(), "script", "<script type='text/javascript'>alert('查询字符串错误');window.close();</script>");
                        return;
                    }
                    LabMS.BLL.Attachment Attach = new LabMS.BLL.Attachment();
                    LabMS.Model.Attachment attachmodel = new LabMS.Model.Attachment();
                    attachmodel = Attach.GetModel(int.Parse(Request.QueryString["ID"].Trim()));
                    Gv_DataBind(attachmodel);
                }
            }
            //if (Request.QueryString["ID"] == null)
            //{
            //    Common.JShelper.JSAlert(Page, "err", "参数错误!");
            //    return;
            //}
            //else if (Request.QueryString["ID"] != null && Request.QueryString["type"] == null)
            //{
            //    int iTemp = 0;
            //    string strID = Request.QueryString["ID"].ToString();
            //    if (!int.TryParse(strID, out iTemp))
            //    {
            //        Common.JShelper.JSAlert(Page, "err", "参数错误!");
            //        return;
            //    }
            //    LabMS.Model.Attachment mattach = new LabMS.Model.Attachment();
            //    LabMS.BLL.Attachment battach = new LabMS.BLL.Attachment();
            //    mattach = battach.GetModel(iTemp);
            //    if (mattach.Attach_Name == "")
            //    {
            //        Response.Redirect("DownloadFile.aspx?ID=" + strID + "&type=1");
            //    }
            //    else
            //    {
            //        string FullFileName = mattach.Attach_Address;
            //        string FileName = mattach.Attach_Name;
            //        try
            //        {
            //            FullFileName = Server.MapPath("../" + FullFileName);
            //            Context.Response.Buffer = true;
            //            Context.Response.Clear();
            //            Context.Response.AppendHeader("Content-Disposition ", "attachment;filename= " + HttpUtility.UrlEncode(FullFileName, System.Text.Encoding.UTF8));
            //            Response.ContentType = "application/x-zip-compressed";
            //            Response.TransmitFile(FullFileName);
            //        }
            //        catch
            //        {
            //            Common.JShelper.JSAlert(Page, "err", "路径错误!");
            //            return;
            //        }
            //        Response.End();
            //    }
            //}
            //else if (Request.QueryString["ID"] != null && Request.QueryString["type"] != null)
            //{
            //    if (Request.QueryString["type"].ToString().Equals("1"))
            //    {
            //        List<LabMS.Model.AttachmentItem> listattchitem = new List<LabMS.Model.AttachmentItem>();
            //        LabMS.BLL.AttachmentItem battachitem = new LabMS.BLL.AttachmentItem();
            //        int iTemp = 0;
            //        string strID = Request.QueryString["ID"].ToString();
            //        if (!int.TryParse(strID, out iTemp))
            //        {
            //            Common.JShelper.JSAlert(Page, "err", "参数错误!");
            //            return;
            //        }
            //        listattchitem = battachitem.GetModelList("Attach_ID = " + strID);
            //        foreach (LabMS.Model.AttachmentItem mai in listattchitem)
            //        {
            //            mai.Item_Address = "<a onclick=foo('DownloadFile.aspx?type=2&ID=" + mai.ID.ToString() + "')>点击下载</a>";
            //        }
            //        gvFile.DataSource = listattchitem;
            //        gvFile.DataBind();
            //        gvFile.Visible = true;
            //    }
            //    else if (Request.QueryString["type"].ToString().Equals("2"))
            //    {
            //        int iTemp = 0;
            //        string strID = Request.QueryString["ID"].ToString();
            //        if (!int.TryParse(strID, out iTemp))
            //        {
            //            Common.JShelper.JSAlert(Page, "err", "参数错误!");
            //            return;
            //        }
            //        LabMS.Model.AttachmentItem mattach = new LabMS.Model.AttachmentItem();
            //        LabMS.BLL.AttachmentItem battach = new LabMS.BLL.AttachmentItem();
            //        mattach = battach.GetModel(iTemp);
            //        string FullFileName = mattach.Item_Address;

            //        string FileName = mattach.Item_Name;
            //        try
            //        {
            //            FullFileName = Server.MapPath("../" + FullFileName);
            //            Context.Response.Buffer = true;
            //            Context.Response.Clear();
            //            Context.Response.AppendHeader("Content-Disposition ", "attachment;filename= " + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
            //            Response.ContentType = "application/x-zip-compressed";
            //            Response.TransmitFile(FullFileName);
            //        }
            //        catch
            //        {
            //            Common.JShelper.JSAlert(Page, "err", "路径错误!");
            //            return;
            //        }
            //        Response.End();

            //    }
            //}
        }


        //
        protected void Gv_DataBind(LabMS.Model.Attachment attach) 
        {

            if (attach.Attach_Name == "")
            {
                string type="";
                if (!string.IsNullOrEmpty(Request.QueryString["Type"]))
                {
                    if (IsNumber(Request.QueryString["Type"]))
                    {
                        type = Request.QueryString["Type"].Trim();
                    }
                }
                else 
                {
                    type = "";
                }
                LabMS.BLL.AttachmentItem AttachItem = new LabMS.BLL.AttachmentItem();
                List<LabMS.Model.AttachmentItem> ls = new List<LabMS.Model.AttachmentItem>();
                if (type != "")
                {
                    ls = AttachItem.GetModelList("Attach_ID=" + attach.ID + " and Item_Type=" + type);
                }
                else 
                {
                    ls = AttachItem.GetModelList("Attach_ID=" + attach.ID);
                }
                Gv_FileItem.DataSource = ls;
                Gv_FileItem.DataBind();
                Gv_FileItem.Visible = true;
                
            }
            else 
            {
                List<LabMS.Model.Attachment> ls = new List<LabMS.Model.Attachment>();
                ls.Add(attach);
                Gv_File.DataSource = ls;
                Gv_File.DataBind();
                Gv_File.Visible = true;
            }
        }
        protected string GetItemTypeString(object value) 
        {
           
            string type = value.ToString();
            switch (type)
            {
                case "1":
                    return "项目申请书";
                    
                case "2":
                    return "项目任务书";
                   
                case "3":
                    return "项目评审书";

            }
            return "";

        }

        protected string GetTypeString(object value) 
        {
            string type = value.ToString();
            switch(type) 
            {
                case "1":
                    return "课程大纲";
                case "2":
                    return "实验指导书";
            }
            return "";
        }

        protected void Gv_FileItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DownLoad") 
            {
                
                int ItemID=0;
                if(int.TryParse(Gv_FileItem.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["ID"].ToString(),out ItemID))
                {
                    FileItemDownload(ItemID, Gv_FileItem.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Item_Address"].ToString(), Gv_FileItem.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Item_Name"].ToString());
                }
            }
        }
        protected bool IsNumber(String strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");

            return !objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber);
        }

        protected void Gv_File_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DownLoad")
            {
                int AttachID = 0;
                
                if (int.TryParse(Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["ID"].ToString(),out AttachID))
                {
                    FileItemDownload(AttachID, Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Attach_Address"].ToString(), Gv_File.DataKeys[int.Parse(e.CommandArgument.ToString())].Values["Attach_Name"].ToString());
                }
            }
        }


        private void FileItemDownload(int itemID,string address,string filename)
        {
            if (itemID == 0) 
            {
                lb_Error.Text = "附件参数错误";
                return;
            }

            System.IO.Stream iStream = null;
            try
            {
                

                string fullpath = Server.MapPath("../" + address);
                if (System.IO.File.Exists(fullpath))
                {
                    Response.Clear();
                    Response.Charset = "UTF-8";
                    Response.Buffer = true;
                    Response.ContentEncoding = System.Text.Encoding.UTF8;
                    Response.HeaderEncoding = System.Text.Encoding.UTF8;
                    HttpBrowserCapabilities br = HttpContext.Current.Request.Browser;
                    string strTemp = filename;//System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);/

                    byte[] buffer = new byte[100000];
                    int iLength;
                    long dataToRead;
                    iStream = new FileStream(fullpath, FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    dataToRead = iStream.Length;

                    Response.ContentType = "application/octet-stream";

                    if (br.Browser == "IE")
                    {
                        strTemp = HttpUtility.UrlEncode(strTemp);
                        
                        strTemp = strTemp.Replace("+", "%20");
                        Response.AppendHeader("Content-Disposition", "attachment;filename=" + strTemp);
                    }
                    else 
                    {
                        strTemp = strTemp.Replace(" ", "");
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + strTemp);

                    }
                    
                    
                    while (dataToRead > 0)
                    {
                        if (Response.IsClientConnected)
                        {
                            iLength = iStream.Read(buffer, 0, 100000);
                            Response.BinaryWrite(buffer);
                            Response.Flush();
                            buffer = new byte[100000];
                            dataToRead = dataToRead - iLength;
                        }
                        else
                        {
                            dataToRead = -1;
                        }
                    }
                }



            }
            catch (Exception ex)
            {
                lb_Error.Text = ex.Message;

            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
            }
        }
    }
}
